'use strict'
exports.main = async () => {
  const tcb = require('@cloudbase/node-sdk')
  const app = tcb.init()
  const db = app.database()
  const startdate = Date.now() + 86400000
  const res = await db.collection('sslorder').where({
    autoNewOrder: db.command.neq('nearexpire'),
    isAutoNewOrder: false,
    isNoticeCertificateNearexpire: false,
    certificateEndDate: db.command.lte(startdate),
    status: 'valid'
  }).get()
  res.data.forEach(async (item) => {
    await db.collection('sslorder').where({
      _id: item._id
    }).update({
      isNoticeCertificateNearexpire: true
    })
    app.callFunction({
      name: 'sendEmail',
      data: {
        uid: item.uid,
        noticeName: 'ssl_email_certificatenearexpire',
        subject: 'SSL证书证书即将到期提醒',
        text: '您的账号“SSL证书”产品证书（订单ID：' + item._id + '，首域名：' + item.domains[0] + '）' + '将于1天内到期。'
      }
    })
    app.callFunction({
      name: 'sendWebhook',
      data: {
        uid: item.uid,
        data: {
          noticeName: 'ssl_webhook_certificatenearexpire',
          orderId: item._id,
          domains: item.domains
        }
      }
    })
  })
}